// pages/needHelp/create/create.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"

const app = getApp()
// 录音管理器
const recorderManager = wx.getRecorderManager()
// 声音播放管理器
const audioPlayer = wx.createInnerAudioContext();

Page({

  /**
   * 创建预约
   */

  /**
   * 页面的初始数据
   */
  data: {
    // 上锁
    is_recording: false,
    // 是否发送消息
    ifSendMsgRecord: false,
    // 已录音频长度
    audioLengthRecord: 0,
    showCancelSendRecord: false,
    sendMsgBtnTextRecord: "按住说话",
    cancelTipTextRecord: "滑动到此处松手取消发送",
    isDisable: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 获取页面高度，用户信息
    this.data.height = wx.getSystemInfoSync().windowHeight

    // 录音开始的回调函数
    recorderManager.onStart((res) => {
      console.log("录音开始")
    })

    // 录音停止的回调函数
    recorderManager.onStop((res) => {
      var that = this
      console.log("判断是否发送录音")
      clearInterval(this.data.audioPercentageInterval)
      // 重值状态
      this.setData({
        showCancelSendRecord: false,
        audioLengthRecord: 0,
        sendMsgBtnTextRecord: "按住说话",
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })

      //此时先判断是否需要发送录音
      if (this.data.ifSendMsgRecord == false) {
        console.log("不发送录音*********")
        return
      }

      console.log("发送录音*********")
      this.setData({
        // 重置状态
        ifSendMsgRecord: false
      })

      const duration = res.duration
      console.log(duration)
      //对录音时长进行判断，少于2s的不进行发送，并做出提示
      if (duration < 2000) {
        console.log("录音时间太短")
        // TODO 语音提示 录音时间太短小于两秒，请长按录音
        app.textToSpeech('录音时间太短，请长按录音').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
        that.setData({
          isDisable: false
        })
      } else {
        //进行语音发送
        that.sendAppointment(res.tempFilePath, duration).then((res) => {
          console.log(res)
          // TODO 语音提示 发送成功，自动为您跳转首页
          app.textToSpeech('发送成功，将为您跳转首页').then((res) => {
            audioPlayer.src = res
            audioPlayer.play()
          })
          this.returnToIndex = true
        }).catch((err) => {
          console.log(err)
          // TODO 语音提示 发送失败，请检查网络后重试
          app.textToSpeech('发送失败，请检稍后重试').then((res) => {
            audioPlayer.src = res
            audioPlayer.play()
          })
          that.setData({
            isDisable: false
          })
        })
      }
    })

    // 自然播放结束
    audioPlayer.onEnded(() => {
      if (this.returnToIndex) {
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },

  sendAppointment: function(tempFilePath, duration) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        header: API.REQUEST_HEADER,
        url: API.FILE_UPLOAD,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          fileProp: API.fILE_PROP_APPOINTMENT
        },
        success: function(res) {
          let result = JSON.parse(res.data)
          console.log(result)
          let id = app.globalData.openId + API.SEPARATOR + Date.now()
          if (result.code == 20000) {
            requestUtil.post(API.CREATE_APPOINTMENT, {
              "id": id,
              "createTime": new Date().format(),
              "msgType": "audio",
              "content": result.data.fileName,
              "duration": Math.ceil(duration),
              "fromUserOpenId": app.globalData.openId,
              "msgStatus": 0,
              "fromUserAvatarUrl": app.globalData.userInfo.avatarUrl,
              "fromUserNickName": app.globalData.userInfo.nickName
            }).then(res => {
              resolve(res)
            }).catch(err => {
              reject(err)
            })
          } else {
            reject("上传失败，所以发送失败")
          }
        },
        fail: function(err) {
          reject(err)
        }
      })
    })
  },

  // 手指按下
  handleRecordStart: function(e) {

    if (this.data.is_recording == false) {
      console.log("++++++++++++++++++++按下按钮")
      audioPlayer.stop()

      wx.vibrateLong()

      // TODO 语音提示 开始录音
      // app.textToSpeech('开始录音').then((res) => {
      //   audioPlayer.src = res
      //   audioPlayer.play()
      // })

      clearInterval(this.data.audioPercentageInterval)
      this.setData({
        audioLengthRecord: 0,
        is_recording: true, // 开始录音标志
        ifSendMsgRecord: true, // 默认发送录音
        startPointY: e.touches[0].clientY, //记录第一个触摸点的Y坐标信息
        showCancelSendRecord: true,
        sendMsgBtnTextRecord: "松开发送"
      })
      // 设置录音参数并开始录音
      console.log("录制预约消息")
      recorderManager.start({
        duration: 60000,
        format: "mp3"
      });

      this.data.audioPercentageInterval = setInterval(() => {
        var audioLengthRecord = this.data.audioLengthRecord + 1
        this.setData({
          audioLengthRecord: audioLengthRecord
        })
      }, 1000)
    }
  },

  // 手指离开
  handleRecordStop: function(e) {
    console.log(e.touches.length)
    if (e.touches.length == 0) {
      console.log("---------------------离开按钮")
      // TODO 语音提示，录音结束

      if(this.data.ifSendMsgRecord){
        app.textToSpeech('录音结束').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
      }else{
        app.textToSpeech('您取消了发送').then((res) => {
          audioPlayer.src = res
          audioPlayer.play()
        })
      }
      
      recorderManager.stop() //结束录音
      this.setData({
        is_recording: false,
        isDisable: true
      })
    }
  },

  // 手指移动
  handleTouchMove: function(event) {
    // console.log("滑动中########")
    //计算垂直滑动距离
    if (event.touches[0].clientY <= this.data.height * 0.73 && this.data.cancelTipTextRecord != "松开 取消") {
      this.setData({
        ifSendMsgRecord: false,
        cancelTipTextRecord: "松开 取消"
      })
      // TODO 语音提示 现在松手即可取消发送
      app.textToSpeech('现在松手即可取消发送').then((res) => {
        audioPlayer.src = res
        audioPlayer.play()
      })
    } else if (event.touches[0].clientY > this.data.height * 0.73 && this.data.cancelTipTextRecord != "滑动到此处松手取消发送") {
      this.setData({
        ifSendMsgRecord: true,
        cancelTipTextRecord: "滑动到此处松手取消发送"
      })
      // TODO 语音提示 现在松手即可发送
      app.textToSpeech('现在松手即可发送').then((res) => {
        audioPlayer.src = res
        audioPlayer.play()
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.returnToIndex = false
    this.setData({
      isDisable: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    audioPlayer.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    audioPlayer.destroy()
  },
})